package org.example.company.filter;

import org.example.common.Constant;
import org.example.company.config.JwtProperties;
import org.example.company.utils.JwtTokenUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class JwtTokenAuthenticationFailter implements WebFilter {

    private final JwtProperties jwtProperties;

    public JwtTokenAuthenticationFailter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String token = getTokenFromHeaders(exchange.getRequest());
        if (StringUtils.hasLength(token)) {
            //验证token的有效性,并解析其中的用户信息。
            Authentication authentication = JwtTokenUtils.getAuthentication(token, jwtProperties.getSecurityKey());
            if (authentication!=null) {
                //chain.filter(exchange)：继续执行过滤链，传递当前的 ServerWebExchange 对象。
                //.subscriberContext(...)：修改 Reactive 上下文，通过 ReactiveSecurityContextHolder.withAuthentication(authentication)
                // 将 Authentication 对象设置到当前的 Reactive 安全上下文中。
                return chain.filter(exchange)
                        .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
            }

        }
        return chain.filter(exchange);
    }

    private String getTokenFromHeaders(ServerHttpRequest serverHttpRequest){
        String x_toekn = serverHttpRequest.getHeaders().getFirst(Constant.TOKEN);
        if (StringUtils.hasLength(x_toekn)){
            return x_toekn;
        }
        return null;
    }
}
